import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import '../services/file_service.dart';
import '../services/directory_service.dart';
import '../models/directory_model.dart';
import '../models/file_item.dart';
import '../widgets/file_picker_sheet.dart';
import '../widgets/file_folder_list_view.dart';
import 'file_preview_page.dart';
import '../services/auth_service.dart';
import '../pages/login_page.dart';
import '../pages/recycle_bin_page.dart';
import '../screens/upload_tasks_screen.dart';
import 'package:flutter/foundation.dart';
import '../services/upload/core/upload_manager.dart';
import '../widgets/file_list_view.dart';
import '../utils/file_picker_utils.dart';
import 'dart:io';
import 'dart:async';
import '../routes.dart';

class FileUploadPage extends StatefulWidget {
  final Function(bool)? onSelectModeChanged;

  const FileUploadPage({super.key, this.onSelectModeChanged});

  @override
  State<FileUploadPage> createState() => _FileUploadPageState();
}

class _FileUploadPageState extends State<FileUploadPage> {
  final List<FileItem> _files = [];
  List<DirectoryModel> _directories = [];
  final DirectoryService _directoryService = DirectoryService();
  bool _isLoading = false;
  bool _isUploading = false;
  bool _isDeleting = false;
  bool _isSelectMode = false;
  bool _isError = false;
  int _currentPage = 1;
  int _totalFiles = 0;
  int _currentDirectoryId = 0;
  String _currentDirectoryName = '文件';
  static const int _pageSize = 20;
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();
  Set<int> _selectedFileIds = <int>{};
  String? _selectedFileType;
  bool _hasMore = true;
  String _errorMsg = '';
  DateTime? _lastBackPressTime;
  bool _showExitToast = false;
  Timer? _exitToastTimer;
  final List<Function(bool)> _selectModeListeners = [];
  StreamSubscription? _fileListUpdateSubscription;

  // 定义文件类型列表
  final List<Map<String, dynamic>> _fileTypes = [
    {'type': 'photo', 'label': '图片', 'icon': Icons.image},
    {'type': 'video', 'label': '视频', 'icon': Icons.video_file},
    {'type': 'audio', 'label': '音频', 'icon': Icons.audio_file},
    {'type': 'document', 'label': '文档', 'icon': Icons.description},
    {'type': 'other', 'label': '其他', 'icon': Icons.insert_drive_file},
  ];

  @override
  void initState() {
    super.initState();
    // 先添加监听器，再加载文件
    _scrollController.addListener(_onScroll);

    // 监听文件列表更新通知
    _fileListUpdateSubscription = FileService.fileListUpdateStream.listen((_) {
      if (mounted) {
        // 收到通知后刷新文件列表
        _loadFiles(true);
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) _loadFiles();
    });
  }

  @override
  void dispose() {
    // 取消文件列表更新监听
    _fileListUpdateSubscription?.cancel();

    // 移除监听器后再销毁控制器
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    _searchController.dispose();
    _exitToastTimer?.cancel();
    super.dispose();
  }

  // 滚动监听，实现上拉加载更多
  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      _loadMoreFiles();
    }
  }

  // 加载文件列表
  Future<void> _loadFiles([bool refresh = false]) async {
    if (_isLoading) return;

    if (refresh) {
      setState(() {
        _currentPage = 1;
        _hasMore = true;
        _files.clear();
        _isLoading = true;
      });
    } else if (!_hasMore) {
      return;
    } else {
      setState(() {
        _isLoading = true;
      });
    }

    try {
      // 加载目录
      final directories = await _directoryService.getDirectories(
        parentId: _currentDirectoryId,
      );

      setState(() {
        _directories = directories;
      });

      // 加载文件
      final response = await FileService.getFileList(
        page: _currentPage,
        pageSize: _pageSize,
        fileType: _selectedFileType,
        keyword: _searchController.text,
        directoryId: _currentDirectoryId,
      );

      if (!mounted) return;

      setState(() {
        if (response.data != null) {
          if (_currentPage == 1) {
            _files.clear();
            _files.addAll(response.data!.items);
          } else {
            _files.addAll(response.data!.items);
          }
          _hasMore = response.data!.total > _files.length;
          _totalFiles = response.data!.total;
          _currentPage++;
        }
        _isLoading = false;
        _isError = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _isError = true;
        _errorMsg = '加载文件失败：${e.toString()}';
      });
      _showError('加载文件列表失败：$e');
    }
  }

  // 加载更多文件
  Future<void> _loadMoreFiles() async {
    _currentPage++;
    await _loadFiles();
  }

  // 选择并上传文件
  Future<void> _pickAndUploadFile() async {
    // 传递当前目录ID给文件选择器
    final result = await FilePickerUtils.showFilePickerSheet(
      context,
      currentDirectoryId: _currentDirectoryId,
    );
    // 如果需要刷新（例如创建了文件夹），则重新加载文件
    if (result == true) {
      await _loadFiles(true);
    }
  }

  // 批量删除文件和目录
  Future<void> _batchDeleteItems() async {
    if (_selectedFileIds.isEmpty) {
      _showError('请至少选择一个项目');
      return;
    }

    if (!mounted) return;

    // 分离文件ID和目录ID
    final List<int> fileIds = [];
    final List<int> directoryIds = [];

    for (final id in _selectedFileIds) {
      if (id < 0) {
        // 负数ID是目录，转为正数
        directoryIds.add(-id);
      } else {
        // 正数ID是文件
        fileIds.add(id);
      }
    }

    // 计算选中的文件数和目录数
    final int selectedFilesCount = fileIds.length;
    final int selectedDirectoriesCount = directoryIds.length;
    String confirmMessage = '确定要删除';
    if (selectedDirectoriesCount > 0) {
      confirmMessage += ' $selectedDirectoriesCount 个文件夹';
      if (selectedFilesCount > 0) {
        confirmMessage += '和';
      }
    }
    if (selectedFilesCount > 0) {
      confirmMessage += ' $selectedFilesCount 个文件';
    }
    confirmMessage += '吗？';

    if (selectedDirectoriesCount > 0) {
      confirmMessage += '\n\n注意：删除文件夹将同时删除其中的所有子文件和子文件夹。';
    }

    // 显示确认对话框
    final bool? confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('确认删除'),
            content: Text(confirmMessage),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                style: TextButton.styleFrom(foregroundColor: Colors.red),
                child: const Text('删除'),
              ),
            ],
          ),
    );

    if (confirmed != true || !mounted) return;

    try {
      setState(() {
        _isDeleting = true;
      });

      final result = await FileService.batchDeleteItems(
        directoryIds: directoryIds.isNotEmpty ? directoryIds : null,
        fileIds: fileIds.isNotEmpty ? fileIds : null,
      );

      if (!mounted) return;

      // 刷新列表
      _currentPage = 1;
      _files.clear();
      _directories.clear();

      setState(() {
        _isSelectMode = false;
        _selectedFileIds.clear();

        // 通知父组件选择模式已经更改
        if (widget.onSelectModeChanged != null) {
          widget.onSelectModeChanged!(_isSelectMode);
        }
      });

      await _loadFiles(true);

      if (!mounted) return;

      // 解析结果并显示提示
      final directoriesSuccess =
          result.data?.data?['directories']?['success_count'] ?? 0;
      final directoriesAffectedFiles =
          result.data?.data?['directories']?['affected_files_count'] ?? 0;
      final filesSuccess = result.data?.data?['files']?['success_count'] ?? 0;
      final totalSuccess = result.data?.data?['total_success_count'] ?? 0;
      final totalFailed = result.data?.data?['total_failed_count'] ?? 0;

      if (totalFailed > 0) {
        _showWarning('成功删除$totalSuccess个项目，$totalFailed个项目删除失败');
      } else {
        String successMessage = '成功删除';
        if (directoriesSuccess > 0) {
          successMessage += '$directoriesSuccess个文件夹';
          if (directoriesAffectedFiles > 0) {
            successMessage += '（包含$directoriesAffectedFiles个子文件）';
          }
          if (filesSuccess > 0) {
            successMessage += '和';
          }
        }
        if (filesSuccess > 0) {
          successMessage += '$filesSuccess个文件';
        }
        _showSuccess(successMessage);
      }
    } catch (e) {
      if (!mounted) return;
      _showError('删除失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isDeleting = false;
        });
      }
    }
  }

  // 添加选择模式监听器
  void addSelectModeListener(Function(bool) listener) {
    _selectModeListeners.add(listener);
  }

  // 移除选择模式监听器
  void removeSelectModeListener(Function(bool) listener) {
    _selectModeListeners.remove(listener);
  }

  // 通知所有监听器
  void _notifySelectModeChanged(bool isSelectMode) {
    for (final listener in _selectModeListeners) {
      listener(isSelectMode);
    }
  }

  // 切换选择模式
  void _toggleSelectMode() {
    setState(() {
      _isSelectMode = !_isSelectMode;
      if (!_isSelectMode) {
        _selectedFileIds.clear();
      }

      // 通知父组件选择模式已更改
      if (widget.onSelectModeChanged != null) {
        widget.onSelectModeChanged!(_isSelectMode);
      }
    });
  }

  void _showError(String message) {
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.red),
    );
  }

  void _showSuccess(String message) {
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.green),
    );
  }

  void _showWarning(String message) {
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.orange),
    );
  }

  Future<bool> _onWillPop() async {
    if (_currentDirectoryId > 0) {
      await _navigateToParentDirectory();
      return false;
    }

    final now = DateTime.now();
    if (_lastBackPressTime == null ||
        now.difference(_lastBackPressTime!) > const Duration(seconds: 2)) {
      _lastBackPressTime = now;
      setState(() {
        _showExitToast = true;
      });
      _exitToastTimer?.cancel();
      _exitToastTimer = Timer(const Duration(seconds: 2), () {
        if (mounted) {
          setState(() {
            _showExitToast = false;
          });
        }
      });
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Stack(
        children: [
          Scaffold(
            appBar: AppBar(
              centerTitle: true,
              leading:
                  _isSelectMode
                      ? IconButton(
                        icon: const Text('取消', style: TextStyle(fontSize: 16)),
                        onPressed: _toggleSelectMode,
                      )
                      : (_currentDirectoryId > 0
                          ? IconButton(
                            icon: const Icon(Icons.arrow_back),
                            onPressed: _navigateToParentDirectory,
                          )
                          : null),
              title:
                  _isSelectMode
                      ? Text(
                        '已选择 ${_selectedFileIds.length} 个项目',
                        style: Theme.of(context).appBarTheme.titleTextStyle,
                        textAlign: TextAlign.center,
                      )
                      : Text(
                        _currentDirectoryId > 0
                            ? _currentDirectoryName // 显示当前目录名称
                            : (_selectedFileType == null
                                ? '文件 (${_totalFiles}个)'
                                : '${_fileTypes.firstWhere((type) => type['type'] == _selectedFileType)['label']}文件 (${_totalFiles}个)'),
                        style: Theme.of(context).appBarTheme.titleTextStyle,
                        textAlign: TextAlign.center,
                      ),
              backgroundColor: Theme.of(context).primaryColor,
              actions: [
                if (_isUploading)
                  const Padding(
                    padding: EdgeInsets.all(16.0),
                    child: SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    ),
                  ),
                if (_isSelectMode) ...[
                  // 全选按钮
                  IconButton(
                    icon: const Text('全选', style: TextStyle(fontSize: 16)),
                    tooltip:
                        _selectedFileIds.length == _getFilteredFiles().length
                            ? '取消全选'
                            : '全选',
                    onPressed: () {
                      setState(() {
                        if (_selectedFileIds.length ==
                            _getFilteredFiles().length) {
                          _selectedFileIds.clear();
                          // 如果清空了所有选择，退出选择模式
                          _isSelectMode = false;
                          // 通知父组件选择模式已更改
                          if (widget.onSelectModeChanged != null) {
                            widget.onSelectModeChanged!(_isSelectMode);
                          }
                        } else {
                          _selectedFileIds =
                              _getFilteredFiles()
                                  .map((f) => f['id'] as int)
                                  .toSet();
                        }
                      });
                    },
                  ),
                ] else ...[
                  // 添加传输列表按钮
                  IconButton(
                    icon: const Icon(Icons.swap_vert),
                    tooltip: '传输列表',
                    onPressed: () {
                      Navigator.pushNamed(context, Routes.transferList);
                    },
                  ),
                ],
              ],
            ),
            // 显示批量删除按钮和上传按钮
            floatingActionButton: Stack(
              children: [
                // 上传按钮
                Positioned(
                  right: 16,
                  bottom: 16,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      boxShadow: [
                        BoxShadow(
                          color: Theme.of(
                            context,
                          ).primaryColor.withOpacity(0.3),
                          blurRadius: 8,
                          offset: const Offset(0, 4),
                        ),
                      ],
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap:
                            (_isUploading || _isSelectMode)
                                ? null
                                : _pickAndUploadFile,
                        borderRadius: BorderRadius.circular(8),
                        child: Container(
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            color:
                                (_isUploading || _isSelectMode)
                                    ? Theme.of(
                                      context,
                                    ).primaryColor.withOpacity(0.5)
                                    : Theme.of(context).primaryColor,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child:
                              _isUploading
                                  ? const Padding(
                                    padding: EdgeInsets.all(12),
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      valueColor: AlwaysStoppedAnimation<Color>(
                                        Colors.white,
                                      ),
                                    ),
                                  )
                                  : const Icon(
                                    Icons.file_upload,
                                    color: Colors.white,
                                  ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
            bottomNavigationBar:
                _isSelectMode ? _buildSelectModeBottomBar() : null,
            body: Column(
              children: [
                // 文件类型筛选按钮组
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 8,
                  ),
                  child: Row(
                    children: [
                      // 全部类型按钮
                      Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: FilterChip(
                          label: SizedBox(
                            width: 70,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.folder,
                                  size: 18,
                                  color:
                                      _selectedFileType == null
                                          ? Colors.white
                                          : Colors.grey[600],
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  '全部',
                                  style: TextStyle(
                                    color:
                                        _selectedFileType == null
                                            ? Colors.white
                                            : Colors.grey[600],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          selected: _selectedFileType == null,
                          onSelected: (bool selected) {
                            setState(() {
                              _selectedFileType = null;
                              // 重置页码并重新加载文件列表
                              _currentPage = 1;
                              _loadFiles();
                            });
                          },
                          selectedColor: Theme.of(context).primaryColor,
                          checkmarkColor: Colors.white,
                          backgroundColor: Colors.grey[100],
                          showCheckmark: false,
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 5,
                          ),
                          visualDensity: VisualDensity.compact,
                          materialTapTargetSize:
                              MaterialTapTargetSize.shrinkWrap,
                        ),
                      ),
                      // 文件类型筛选按钮
                      ...List.generate(_fileTypes.length, (index) {
                        final type = _fileTypes[index];
                        final isSelected = _selectedFileType == type['type'];
                        return Padding(
                          padding: const EdgeInsets.only(right: 8),
                          child: FilterChip(
                            label: SizedBox(
                              width: 70,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(
                                    type['icon'] as IconData,
                                    size: 18,
                                    color:
                                        isSelected
                                            ? Colors.white
                                            : _getColorForFileType(
                                              type['type'] as String,
                                            ),
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    type['label'] as String,
                                    style: TextStyle(
                                      color:
                                          isSelected
                                              ? Colors.white
                                              : Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            selected: isSelected,
                            onSelected: (bool selected) {
                              setState(() {
                                _selectedFileType =
                                    selected ? type['type'] : null;
                                // 重置页码并重新加载文件列表
                                _currentPage = 1;
                                _loadFiles();
                              });
                            },
                            selectedColor: _getColorForFileType(
                              type['type'] as String,
                            ),
                            checkmarkColor: Colors.white,
                            backgroundColor: Colors.grey[100],
                            showCheckmark: false,
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 5,
                            ),
                            visualDensity: VisualDensity.compact,
                            materialTapTargetSize:
                                MaterialTapTargetSize.shrinkWrap,
                          ),
                        );
                      }),
                    ],
                  ),
                ),
                // 文件列表
                Expanded(
                  child: RefreshIndicator(
                    onRefresh: () async {
                      await _loadFiles(true);
                    },
                    child: FileListView(
                      files: _getFilteredFiles(),
                      isLoading: _isLoading,
                      isSelectMode: _isSelectMode,
                      selectedFileIds: _selectedFileIds,
                      onFileSelected: (fileId) {
                        // 如果不是选择模式，点击选择圆圈时自动开启选择模式
                        if (!_isSelectMode) {
                          setState(() {
                            _isSelectMode = true;
                            _selectedFileIds.add(fileId);

                            // 通知父组件选择模式已更改
                            if (widget.onSelectModeChanged != null) {
                              widget.onSelectModeChanged!(_isSelectMode);
                            }
                          });
                        } else {
                          setState(() {
                            if (_selectedFileIds.contains(fileId)) {
                              _selectedFileIds.remove(fileId);

                              // 如果没有选中项了，自动退出选择模式
                              if (_selectedFileIds.isEmpty) {
                                _isSelectMode = false;
                                // 通知父组件选择模式已更改
                                if (widget.onSelectModeChanged != null) {
                                  widget.onSelectModeChanged!(_isSelectMode);
                                }
                              }
                            } else {
                              _selectedFileIds.add(fileId);
                            }
                          });
                        }
                      },
                      onFileTap: (fileId, fileName, fileType) {
                        // 处理目录点击
                        if (fileType == 'directory') {
                          // fileId是负数，所以需要转换回正数
                          final directoryId = -fileId;
                          setState(() {
                            _currentDirectoryId = directoryId;
                            _currentDirectoryName = fileName;
                            _currentPage = 1;
                            _files.clear();
                            _loadFiles(true);
                          });
                          return;
                        }

                        // 处理普通文件点击
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder:
                                (context) => FilePreviewPage(
                                  fileId: fileId,
                                  fileName: fileName,
                                  fileType: fileType,
                                ),
                          ),
                        );
                      },
                      emptyWidget:
                          (_files.isEmpty && _directories.isEmpty)
                              ? Center(
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    ShaderMask(
                                      shaderCallback: (Rect bounds) {
                                        return LinearGradient(
                                          colors: [
                                            Theme.of(context).primaryColor,
                                            Colors.pinkAccent,
                                          ],
                                        ).createShader(bounds);
                                      },
                                      child: const Icon(Icons.pets, size: 64),
                                    ),
                                    const SizedBox(height: 16),
                                    Text(
                                      '咕噜还没有文件呢~',
                                      style: TextStyle(
                                        color: Theme.of(
                                          context,
                                        ).primaryColor.withOpacity(0.7),
                                        fontSize: 16,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    const SizedBox(height: 8),
                                    Text(
                                      '快点击右下角按钮上传吧！',
                                      style: TextStyle(
                                        color: Colors.grey[600],
                                        fontSize: 14,
                                      ),
                                    ),
                                  ],
                                ),
                              )
                              : null,
                      scrollController: _scrollController,
                    ),
                  ),
                ),
              ],
            ),
          ),
          if (_showExitToast)
            Positioned(
              bottom: 100,
              left: 0,
              right: 0,
              child: Center(
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.black87,
                    borderRadius: BorderRadius.circular(25),
                  ),
                  child: const Text(
                    '再按一次退出应用',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 获取筛选后的文件列表
  List<Map<String, dynamic>> _getFilteredFiles() {
    // 首先处理文件夹
    List<Map<String, dynamic>> result = [];

    // 将目录转换为特殊的"文件"项添加到列表前面
    for (var directory in _directories) {
      result.add({
        'id': -directory.id, // 使用负值ID区分文件夹和文件
        'file_name': directory.name,
        'file_type': 'directory',
        'file_size': 0,
        'upload_time': directory.createTime.toString(),
        'is_directory': true,
        'directory_id': directory.id,
      });
    }

    // 处理文件
    List<FileItem> filteredFiles;
    if (_selectedFileType == null) {
      filteredFiles = _files;
    } else {
      filteredFiles =
          _files.where((file) {
            // 优先使用服务器返回的fileType字段进行筛选
            final fileType = (file.fileType).toLowerCase();
            if (fileType.isNotEmpty) {
              // 直接比较文件类型，将'photo'映射为'image'以匹配服务器返回的类型
              final typeToCompare =
                  _selectedFileType == 'photo' ? 'image' : _selectedFileType;
              if (fileType == typeToCompare) {
                return true;
              }
            }

            // 如果类型不匹配，则检查文件扩展名
            final fileName = (file.filename).toLowerCase();
            if (fileName.isEmpty) {
              return false;
            }

            // 基于文件扩展名进行分类判断（作为备选方案）
            if (_selectedFileType == 'photo') {
              // 图片类型判断：只检查文件扩展名
              final imageExtensions = [
                '.jpg',
                '.jpeg',
                '.png',
                '.gif',
                '.bmp',
                '.webp',
                '.heic',
              ];
              return imageExtensions.any((ext) => fileName.endsWith(ext));
            } else if (_selectedFileType == 'video') {
              // 视频类型判断
              final videoExtensions = [
                '.mp4',
                '.avi',
                '.mov',
                '.wmv',
                '.flv',
                '.mkv',
                '.webm',
              ];
              return videoExtensions.any((ext) => fileName.endsWith(ext));
            } else if (_selectedFileType == 'audio') {
              // 音频类型判断
              final audioExtensions = [
                '.mp3',
                '.wav',
                '.ogg',
                '.m4a',
                '.flac',
                '.aac',
              ];
              return audioExtensions.any((ext) => fileName.endsWith(ext));
            } else if (_selectedFileType == 'document') {
              // 文档类型判断：只检查文件扩展名，不检查文件路径
              final docExtensions = [
                '.pdf',
                '.doc',
                '.docx',
                '.xls',
                '.xlsx',
                '.ppt',
                '.pptx',
                '.txt',
                '.json',
                '.xml',
                '.csv',
              ];
              return docExtensions.any((ext) => fileName.endsWith(ext));
            } else if (_selectedFileType == 'other') {
              // 其他类型判断：不属于上述任何一种类型的文件
              final allKnownExtensions = [
                // 图片
                '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.heic',
                // 视频
                '.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm',
                // 音频
                '.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac',
                // 文档
                '.pdf',
                '.doc',
                '.docx',
                '.xls',
                '.xlsx',
                '.ppt',
                '.pptx',
                '.txt',
                '.json', '.xml', '.csv',
              ];

              // 检查文件扩展名是否匹配任何已知类型
              final hasKnownExtension = allKnownExtensions.any(
                (ext) => fileName.endsWith(ext),
              );

              // 如果有已知扩展名，则不归类为"其他"
              return !hasKnownExtension;
            }

            return false; // 默认不匹配任何类型
          }).toList();
    }

    // 将 FileItem 转换为 Map<String, dynamic>
    result.addAll(
      filteredFiles
          .map(
            (file) => {
              'id': file.id,
              'file_name': file.filename,
              'file_type': file.fileType,
              'file_size': file.size,
              'upload_time': file.uploadTime,
              'is_directory': false,
            },
          )
          .toList(),
    );

    return result;
  }

  Color _getColorForFileType(String fileType) {
    final theme = Theme.of(context);
    if (fileType == 'photo') {
      return theme.primaryColor;
    } else if (fileType == 'video') {
      return Colors.pinkAccent;
    } else if (fileType == 'audio') {
      return Colors.purpleAccent;
    } else if (fileType == 'document') {
      return Colors.deepPurpleAccent;
    } else if (fileType == 'other') {
      return Colors.teal;
    } else {
      return Colors.grey;
    }
  }

  // 导航到上级目录
  Future<void> _navigateToParentDirectory() async {
    if (_currentDirectoryId <= 0) return; // 已经在根目录，不需要返回

    try {
      setState(() {
        _isLoading = true;
      });

      // 获取当前目录的详情，以便获取父目录ID
      final currentDirectory = await _directoryService.getDirectoryDetail(
        _currentDirectoryId,
      );
      final parentId = currentDirectory.parentId;

      // 如果父目录ID为0，表示返回根目录
      final parentName =
          parentId == 0
              ? '文件'
              : (await _directoryService.getDirectoryDetail(parentId)).name;

      setState(() {
        _currentDirectoryId = parentId;
        _currentDirectoryName = parentName;
        _currentPage = 1;
        _files.clear();
        _directories.clear();
        _isLoading = false;
      });

      // 加载父目录的内容
      await _loadFiles(true);
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoading = false;
      });
      _showError('返回上级目录失败: $e');
    }
  }

  Widget _buildSelectModeBottomBar() {
    return SafeArea(
      child: Material(
        elevation: 8,
        child: Container(
          color: Colors.white,
          height: 56,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              // 下载按钮
              _buildBottomBarButton(
                icon: Icons.download_rounded,
                label: '下载',
                onTap: _selectedFileIds.isEmpty ? null : _downloadSelectedFiles,
                isEnabled: _selectedFileIds.isNotEmpty,
              ),

              // 移动按钮
              _buildBottomBarButton(
                icon: Icons.drive_file_move_rounded,
                label: '移动',
                onTap: _selectedFileIds.isEmpty ? null : _moveSelectedFiles,
                isEnabled: _selectedFileIds.isNotEmpty,
              ),

              // 删除按钮
              _buildBottomBarButton(
                icon: Icons.delete_rounded,
                label: '删除',
                onTap: _selectedFileIds.isEmpty ? null : _batchDeleteItems,
                isEnabled: _selectedFileIds.isNotEmpty,
                color: Colors.red,
              ),

              // 分享按钮 (禁用)
              _buildBottomBarButton(
                icon: Icons.share_rounded,
                label: '分享',
                onTap: null,
                isEnabled: false,
              ),

              // 更多按钮 (禁用)
              _buildBottomBarButton(
                icon: Icons.more_horiz_rounded,
                label: '更多',
                onTap: null,
                isEnabled: false,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomBarButton({
    required IconData icon,
    required String label,
    required VoidCallback? onTap,
    required bool isEnabled,
    Color? color,
  }) {
    final buttonColor =
        isEnabled ? (color ?? Theme.of(context).primaryColor) : Colors.grey;

    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, color: buttonColor, size: 24),
          const SizedBox(height: 4),
          Text(label, style: TextStyle(color: buttonColor, fontSize: 12)),
        ],
      ),
    );
  }

  // 下载选中的文件
  void _downloadSelectedFiles() {
    // 过滤出只有文件的ID（忽略目录）
    final fileIds = _selectedFileIds.where((id) => id > 0).toList();
    if (fileIds.isEmpty) {
      _showWarning('请选择至少一个文件进行下载');
      return;
    }

    // 显示下载进度对话框
    _showSuccess('开始下载${fileIds.length}个文件');

    // TODO: 实现文件下载逻辑
  }

  // 移动选中的文件和目录
  void _moveSelectedFiles() {
    // 分离文件ID和目录ID
    final List<int> fileIds = [];
    final List<int> directoryIds = [];

    for (final id in _selectedFileIds) {
      if (id < 0) {
        // 负数ID是目录，转为正数
        directoryIds.add(-id);
      } else {
        // 正数ID是文件
        fileIds.add(id);
      }
    }

    if (fileIds.isEmpty && directoryIds.isEmpty) {
      _showWarning('请选择至少一个项目');
      return;
    }

    // 显示目录选择对话框
    _showSuccess('已选择${fileIds.length}个文件和${directoryIds.length}个文件夹待移动');

    // TODO: 实现显示目录选择器并移动文件和目录的逻辑
  }
}
